import axios from "axios";
import { Message, Modal } from "@arco-design/web-vue";
import { useUserStore } from "@/store";
import { getToken } from "@/utils/auth";

const whiteList = [];
if (import.meta.env.VITE_API_BASE_URL) {
  axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
}

axios.interceptors.request.use(
  (config) => {
    // let each request carry token
    // this example using the JWT token
    // Authorization is a custom headers key
    // please modify it according to the actual situation
    const token = getToken();
    if (token) {
      if (!config.headers) {
        config.headers = {};
      }
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    // do something
    return Promise.reject(error);
  }
);
// add response interceptors
axios.interceptors.response.use(
  (response) => {
    const res = response.data;
    // 如果baseURL 和 config.url的域名 不一样则直接返回
    const baseUrlObj = new URL(response.config.baseURL);
    const requestUrlObj = new URL(response.config.url, baseUrlObj);
    if (baseUrlObj.origin !== requestUrlObj.origin) {
      return response;
    }
    // if the custom code is not 20000, it is judged as an error.
    if (whiteList.includes(response.config.url || "")) {
      return response;
    }
    if (res.code !== 200) {
      Message.error({
        content: res.msg || "数据错误",
        duration: 5 * 1000,
      });
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (
        [401].includes(res.code) &&
        response.config.url !== "/api/user/info"
      ) {
        Modal.error({
          title: "系统提示",
          content: "您已注销，您可以取消停留在此页面，或再次登录",
          okText: "重新登录",
          async onOk() {
            const userStore = useUserStore();

            await userStore.logout();
            window.location.reload();
          },
        });
      }
      return Promise.reject(new Error(res.msg || "加载出错"));
    }
    return res;
  },
  (error) => {
    Message.error({
      content: error.msg || "请求错误",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);
